window.onload = async function() {
    const list = await apiGetMyProducts();
    renderProducts(list);
};

async function deleteProduct(id) {
    if (!confirm('确定要删除该商品吗？')) return;
    const resp = await apiDeleteProduct(id);
    if (resp.ok) {
        window.location.reload();
    } else {
        alert('删除失败');
    }
}

function renderProducts(products) {
    const container = document.getElementById('myProducts');
    if (products.length === 0) {
        container.innerHTML = '暂无商品';
        return;
    }
    container.innerHTML = products.map(p => `
        <div class="product-card">
            <img src="${p.coverImage || 'images/default-product.png'}" 
                 alt="${p.title}" 
                 class="product-image">
            <div class="product-info">
                <h3>${p.title}</h3>
                <p class="price">¥${Number(p.price).toFixed(2)}</p>
                <p class="status ${p.status || 'selling'}">${
        (p.status === 'sold') ? '已售出' : '出售中'
    }</p>
                ${p.images && p.images.length > 0 ? `
                <div class="product-images">
                    ${p.images.map(img => `
                        <img src="${img}" class="thumbnail" alt="${p.title} 图片">
                    `).join('')}
                </div>
                ` : ''}
                <div class="product-actions">
                    <button onclick="editProduct(${p.id})">编辑</button>
                    <button onclick="deleteProduct(${p.id})">删除</button>
                </div>
            </div>
        </div>
    `).join('');
}

// 新增的编辑函数
async function editProduct(id) {
    window.location.href = `/edit-product.html?id=${id}`;
}
